#!/usr/bin/env python
from __future__ import unicode_literals
from flask import g
from flask import Flask
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from werkzeug.local import LocalProxy

app = Flask(__name__, instance_relative_config=True)
app.config.from_object('config.development')


def create_my_engine():
    engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI'],
                           echo=app.config['SQLALCHEMY_ECHO'])
    return engine


def create_session(engine):
    Session = sessionmaker()
    Session.configure(bind=engine)
    return Session()


def get_db():
    db = getattr(g, "_database", None)
    if db is None:
        db = g._database = create_session(create_my_engine())
    return db


#@app.before_request
def before_request():
    get_db()


@app.teardown_appcontext
def teardown_request(excpetion):
    db = getattr(g, '_database', None)
    if db is not None:
        db.close()


# app.teardown_request(teardown_request)
# engine = create_my_engine()
Base = declarative_base()
db = LocalProxy(get_db)
#get_db()
# session = create_session(engine)
